from django.shortcuts import redirect
from django.contrib import messages

from core.lib import auth
from core.lib.auth.vkontakte import get_vk_user_id, APP_ID as VK_APP_ID
from core.lib.auth.facebook import NOT_CORRECT_ID
from core.models import VkontakteCredential
from core.views import index
from core.views.auth.login import login

def process_vkontakte(request):
    try:
        vk_user_cookie = request.COOKIES['vk_app_{0}'.format(VK_APP_ID)]
    except KeyError:
        messages.info(request, 'authorization_error')
    else:
        vk_user_id = get_vk_user_id(vk_user_cookie)
        if vk_user_id != NOT_CORRECT_ID:
            vkontakte_credential = VkontakteCredential(vk_id=vk_user_id)
            user = vkontakte_credential.authenticate()
            if user is None:
                ip = request.META['REMOTE_ADDR']
                user = auth.register(vkontakte_credential, ip)
                messages.info(request, 'automatically_registered')
            request.session['user_id'] = user.id
            return_to = request.GET.get('return_to')
            return redirect(return_to or index)
        else:
            messages.info(request, 'authorization_error')
    return redirect(login)
